package com.quick.develop.flowable.utils;

import com.quick.develop.flowable.framework.cmd.ExpressULCmd;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ManagementService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * @author junyuan.liu
 * @description:  表达式工具类 获取表达式的值、判断表达式
 * @date 2022/5/30 9:27
 */
@Component
@Slf4j
public class ExpressionUtil {
    @Resource
    private ManagementService managementService;

    private static ExpressionUtil expressionUtil;

    // 初始化的时候，将本类中的managementService赋值给静态的本类变量
    @PostConstruct
    public void init() {
        expressionUtil = this;
    }
    
    /** 
     * @description  判断表达式的结果
     * @param data 做判断的数据
     * @param expression 表达式
     * @return boolean
     * @author junyuan.liu
     * @date 2022/6/28 9:11
     */ 
    public static boolean judgeExpression(Map<String,Object> data, String expression){
        Object result = getExpressionValue(data, expression);
        if (result instanceof Boolean) {
            return (boolean) result;
        }
        return false;
    }
    
    /** 
     * @description  获取表达式结果
     * @param data 数据 
     * @param expression 表达式
     * @return java.lang.Object
     * @author junyuan.liu
     * @date 2022/6/28 9:13
     */ 
    public static Object getExpressionValue(Map<String,Object> data, String expression){
        Object result = null;
        try {
            result = expressionUtil.managementService.executeCommand(new ExpressULCmd(expression, data));
        }catch (Exception e){
            log.info("表达式获取结果异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    
}
